﻿using Bigger.Test;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace Ctrip.Demo.RiskPlaform
{
    public class XinZuDemo : BaseDemo
    {
        private static Logger logger = new Logger("");
        private const string loggerName = "XinZuDemo";
        public override void Run()
        {
            XinZuUser userInfo = OnLogin();
            if (userInfo == null)
            {
                return;
            }

            var riskUser = new
            {
                CredentialsNo = "500383198609126714",
                Name = "彭勋星"
            };

            XinZuResponse<string> validResponse = null;
            List<ValidIdResult> validIdResults = null;


            string identityValidUrl = string.Format("http://xzche.xinzuhui.com:9162/xzcheserver/QuerylogTCreditReportquery?userid={0}&skey={1}&identity={2}&name={3}", userInfo.id, userInfo.skey, riskUser.CredentialsNo, HttpUtility.UrlEncode(riskUser.Name));

            logger.Info(loggerName, string.Format("验证信租黑名单接口开始，请求地址：{0}", identityValidUrl));
            HttpWebRequest webRequest = HttpWebRequest.Create(identityValidUrl) as HttpWebRequest;
#if DEBUG

#else
                webRequest.Proxy = new WebProxy("10.14.7.11", 80);
#endif
            using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
            {
                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        string responseString = streamReader.ReadToEnd();
                        logger.Info(loggerName, string.Format("验证信租黑名单接口结束，姓名：{0}，身份证号:{1}，响应结果：{2}", riskUser.Name, riskUser.CredentialsNo, responseString));

                        //接口每200ms请求一次
                        Thread.Sleep(200);

                        if (string.IsNullOrWhiteSpace(responseString))
                        {
                            logger.Info(loggerName, "验证信租黑名单信息失败：验证信租黑名单接口返回数据为空");
                            return;
                        }
                        validResponse = JsonConvert.DeserializeObject<XinZuResponse<string>>(responseString);
                        if (validResponse == null)
                        {
                            logger.Info(loggerName, "验证信租黑名单信息失败：验证信租黑名单接口响应结果为空");
                            return;
                        }
                        if (validResponse.IsSkeyNotCorrect())
                        {
                            logger.Info(loggerName, string.Format("验证信租黑名单信息失败：{0}", validResponse.errmsg));
                            return;
                        }
                        if (!validResponse.IsSuccess())
                        {
                            logger.Info(loggerName, string.Format("验证信租黑名单信息失败：{0}", validResponse.errmsg));
                            return;
                        }
                        //返回的Content为String，需要另外反序列化
                        validIdResults = JsonConvert.DeserializeObject<List<ValidIdResult>>(validResponse.content);
                        if (validIdResults == null || validIdResults.Count <= 0)
                        {
                            //非黑名单
                            return;
                        }
                        //黑名单处理
                        ValidIdResult validIdResult = validIdResults[0];
                        logger.Warn(loggerName, "黑名单用户：" + JsonConvert.SerializeObject(validIdResult));

                    }
                }
            }
        }

        /// <summary>
        /// 模拟登录并获取用户信息
        /// </summary>
        /// <returns></returns>
        private XinZuUser OnLogin()
        {
            string userName = ConfigurationManager.AppSettings["userName"];//13120893657
            string password = ConfigurationManager.AppSettings["password"];//37040254b7f47c2010d8587bd5d5f4da

            XinZuUser xinZuUser = null;
            string loginUrl = string.Format("http://xzche.xinzuhui.com:9162/xzcheserver/CompanyuserinfoTLogin?mobile={0}&password={1}", userName, password);


            logger.Info(loggerName, "模拟登录并获取用户信息 开始");


            HttpWebRequest webRequest = HttpWebRequest.Create(loginUrl) as HttpWebRequest;
#if DEBUG

#else
                webRequest.Proxy = new WebProxy("10.14.7.11", 80);
#endif
            using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
            {
                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        string responseString = streamReader.ReadToEnd();
                        logger.Info(loggerName, string.Format("模拟登录并获取用户信息 结束，响应信息：{0}", responseString));

                        if (string.IsNullOrWhiteSpace(responseString))
                        {
                            logger.Info(loggerName, "信租模拟登录失败：信租模拟登录接口返回数据为空");
                            return xinZuUser;
                        }
                        XinZuResponse<XinZuUser> loginResponse = JsonConvert.DeserializeObject<XinZuResponse<XinZuUser>>(responseString);
                        if (loginResponse == null)
                        {
                            logger.Info(loggerName, "信租模拟登录失败：信租模拟登录接口响应结果为空");
                            return xinZuUser;
                        }
                        if (!loginResponse.IsSuccess())
                        {
                            logger.Info(loggerName, string.Format("信租模拟登录失败：{0}", loginResponse.errmsg));
                            return xinZuUser;
                        }
                        if (loginResponse.content == null)
                        {
                            logger.Info(loggerName, "信租模拟登录失败：返回用户信息为空");
                        }

                        xinZuUser = loginResponse.content;
                        xinZuUser.password = password;
                        return xinZuUser;
                    }
                }
            }
        }
    }
}
